package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.config.goods.GoodsBagInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.usercenter.newadmin.CenterReloadHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 锦盒
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CenterBrocadeBoxAdminController {

    private static Logger logger = LogManager.getLogger(CenterBrocadeBoxAdminController.class.getName());

    /**
     *  48.1 获取该渠道下最大的锦盒id
     */
    @ResponseBody
    @RequestMapping(value = "maxBrocadeBoxId", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String maxBrocadeBoxId(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int boxMaxId = new AdminCommonDaoImpl().getChannelBrocadeBoxMaxId(channelId);

        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("msg", "操作成功");
        result.put("brocadeBoxId", boxMaxId + 1);
        return result.toJSONString();
    }

    /**
     *  48.2 新增
     */
    @ResponseBody
    @RequestMapping(value = "addBrocadeBox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addBrocadeBox(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int boxMaxId = jsonObject.getIntValue("brocadeBoxId");

        int brocadeBoxQuality = jsonObject.getIntValue("brocadeBoxQuality");
        int batchUseCount = jsonObject.getIntValue("batchUseCount");
        int brocadeBoxIconId = jsonObject.getIntValue("brocadeBoxIconId");
        int area = jsonObject.getIntValue("area");
        int freeze = 0;
        if(jsonObject.containsKey("freeze")){
            freeze  = jsonObject.getIntValue("freeze");
        }
        int brocadeBoxType = jsonObject.getIntValue("brocadeBoxType");
        String chineseName = jsonObject.getString("chineseName");
        String chineseDescription = jsonObject.getString("chineseDescription");

        int b = new AdminCommonDaoImpl().selectBrocadeByName(channelId, chineseName);
        if(b > 0){
            return AdminResult.defaultInstance().setMsg("已存在相同名称的锦盒").toJsonString();
        }

        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsId(boxMaxId);
        goodsInfo.setArea(area);
        goodsInfo.setType(brocadeBoxType);
        goodsInfo.setQuality(brocadeBoxQuality);
        goodsInfo.setTopLimit(batchUseCount);
        goodsInfo.setCanUse(batchUseCount);
        goodsInfo.setIcon(String.valueOf(brocadeBoxIconId));
        goodsInfo.setCanBagUse(freeze != 1);
        goodsInfo.setGoodsName(chineseName);
        goodsInfo.setGoodsDesc(chineseDescription);

        List<GoodsBagInfo> childList = new ArrayList<>();

        List<Map<String, Object>> languageList = getLanguage(jsonObject, channelId, boxMaxId);
        JSONArray jsonArray;

        jsonArray = jsonObject.getJSONArray("brocadeBoxContentList");
        int bagMaxId = new AdminCommonDaoImpl().getChannelBrocadeBoxItemMaxId(channelId) + 1;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONArray pool = jsonArray.getJSONArray(i);
            for (int j = 0; j < pool.size(); j++) {
                JSONObject object = pool.getJSONObject(j);
                GoodsBagInfo goodsBagInfo = new GoodsBagInfo();
                int propId = object.getIntValue("propId");
                int num = object.getIntValue("num");
                int weight = object.getIntValue("weight");
                goodsBagInfo.setId(bagMaxId++);
                goodsBagInfo.setBagId(boxMaxId);
                goodsBagInfo.setGoodsId(propId);
                goodsBagInfo.setRandomType(i);
                goodsBagInfo.setMinNum(num);
                goodsBagInfo.setMaxNum(num);
                goodsBagInfo.setRandomWeight(weight);
                childList.add(goodsBagInfo);
            }
        }

        boolean add = new AdminCommonDaoImpl().addBrocade(channelId, goodsInfo, childList, languageList);
        if(!add){
            return AdminResult.defaultInstance().setMsg("新增失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    private List<Map<String, Object>> getLanguage(JSONObject jsonObject, int channelId, int boxMaxId) {
        String chineseName = jsonObject.getString("chineseName");
        String chineseDescription = jsonObject.getString("chineseDescription");

        List<Map<String, Object>> languageList = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONArray("lists");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            String language = object.getString("language");

            String localName = object.getString("localName");
            if(!StringUtils.isNullOrEmpty(localName)){
                Map<String, Object> nameMap = new HashMap<>();
                nameMap.put("key", chineseName);
                nameMap.put("language", language);
                nameMap.put("content", localName);
                nameMap.put("channelId", channelId);
                nameMap.put("type", 4);
                nameMap.put("f_id", String.valueOf(boxMaxId));
                languageList.add(nameMap);
            }
            String localDescription = object.getString("localDescription");
            if(!StringUtils.isNullOrEmpty(localDescription)){
                Map<String, Object> descMap = new HashMap<>();
                descMap.put("key", chineseDescription);
                descMap.put("language", language);
                descMap.put("content", localDescription);
                descMap.put("channelId", channelId);
                descMap.put("type", 4);
                descMap.put("f_id", String.valueOf(boxMaxId));
                languageList.add(descMap);
            }
        }
        return languageList;
    }

    /**
     *  48.3 编辑
     */
    @ResponseBody
    @RequestMapping(value = "editBrocadeBox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String editBrocadeBox(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        AdminResult result = delBrocadeBox(request, jsonObject);
        if(!"操作成功".equals(result.getMsg())){
            return result.toJsonString();
        }

        return addBrocadeBox(request, jsonObject);
    }

    /**
     *  48.4 删除
     */
    @ResponseBody
    @RequestMapping(value = "delBrocadeBox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AdminResult delBrocadeBox(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int boxMaxId = jsonObject.getIntValue("brocadeBoxId");

        //删除
        boolean result = new AdminCommonDaoImpl().deleteChannelBrocadeBox(boxMaxId, channelId);
        if(result){
            boolean del = new AdminCommonDaoImpl().deleteChannelBrocadeBoxItems(boxMaxId, channelId);
            if(!del){
                logger.error("删除锦盒{}明细项，失败", boxMaxId);
            }
            del = new AdminCommonDaoImpl().deleteChannelBrocadeBoxLanguage(String.valueOf(boxMaxId), channelId);
            if(!del){
                logger.error("删除锦盒{}多语言，失败", boxMaxId);
            }
        }else {
            return AdminResult.failMsg("删除失败").setCode(200);
        }
        return AdminResult.defaultInstance();
    }

    /**
     *  48.5 查询
     */
    @ResponseBody
    @RequestMapping(value = "searchBrocadeBox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AdminResult searchBrocadeBox(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int brocadeBoxId = 0;
        if(jsonObject.containsKey("brocadeBoxId")){
            brocadeBoxId = jsonObject.getIntValue("brocadeBoxId");
        }

        String chineseName = "";
        if(jsonObject.containsKey("chineseName")){
            chineseName = jsonObject.getString("chineseName");
        }

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");
        List<Integer> allIdList;
        if(brocadeBoxId > 0){
            allIdList = new AdminCommonDaoImpl().getBroacdeBoxId(brocadeBoxId, channelId);
        }else if(!StringUtils.isNullOrEmpty(chineseName)){
            allIdList = new AdminCommonDaoImpl().getBroacdeBoxId(chineseName, channelId);
        }else {
            //全部查询
            allIdList = new AdminCommonDaoImpl().getBroacdeBoxId(channelId);
        }

        if(allIdList.isEmpty()){
            AdminResult result = AdminResult.defaultInstance();
            result.getData().put("total", 0);
            return result;
        }

        List<Integer> searchIdList = new ArrayList<>();
        //分页
        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);
        for (int i = startIndex; i < startIndex + pageSize && i < allIdList.size(); i++) {
            searchIdList.add(allIdList.get(i));
        }

        //查询主数据
        List<GoodsInfo> goodsInfoList = new AdminCommonDaoImpl().getBroacdeBoxList(channelId, searchIdList);

        Map<Integer, List<GoodsBagInfo>> broacdeBoxDetail = new AdminCommonDaoImpl().getBroacdeBoxDetail(searchIdList, channelId);

        Map<Integer, List<Map<String, Object>>> broacdeBoxLanuage = new AdminCommonDaoImpl().getBroacdeBoxLanuage(searchIdList, channelId);

        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("total", allIdList.size());

        //瓶装数据
        JSONArray row = new JSONArray();
        for (GoodsInfo goodsInfo : goodsInfoList) {
            JSONObject boxObject = new JSONObject();
            boxObject.put("brocadeBoxId", goodsInfo.getGoodsId());
            boxObject.put("brocadeBoxQuality", goodsInfo.getQuality());
            boxObject.put("batchUseCount", goodsInfo.getTopLimit());
            boxObject.put("brocadeBoxIconId", goodsInfo.getIcon());
            boxObject.put("brocadeBoxType", goodsInfo.getType());
            boxObject.put("freeze", goodsInfo.isCanBagUse() ? 0 : 1);

            boxObject.put("chineseName", goodsInfo.getGoodsName());
            boxObject.put("chineseDescription", goodsInfo.getGoodsDesc());
            boxObject.put("area", goodsInfo.getArea());

            List<Map<String, Object>> langList = broacdeBoxLanuage.getOrDefault(goodsInfo.getGoodsId(), Collections.emptyList());
            //按多语言进行合并
            if(!langList.isEmpty()){
                Map<String, Map<String, Object>> localMap = new HashMap<>();
                for (Map<String, Object> objectMap : langList) {
                    String language = (String)objectMap.get("language");
                    if(!localMap.containsKey(language)){
                        localMap.put(language, new HashMap<>());
                    }
                    //旧后台修改都是type=4,奇葩
                    Object content = objectMap.get("content");
                    Object key = objectMap.get("key");
                    if(Objects.equals(goodsInfo.getGoodsName(), key)){
                        localMap.get(language).put("localName", content);
                    }else {
                        localMap.get(language).put("localDescription", content);
                    }
                }
                JSONArray langArray = new JSONArray();
                for (Map.Entry<String, Map<String, Object>> entry : localMap.entrySet()) {
                    JSONObject lanObject = new JSONObject();
                    lanObject.put("language", entry.getKey());
                    lanObject.put("localName", entry.getValue().getOrDefault("localName", ""));
                    lanObject.put("localDescription", entry.getValue().getOrDefault("localDescription", ""));
                    langArray.add(lanObject);
                }
                boxObject.put("lists", langArray);
            }

            List<GoodsBagInfo> goodsBagInfoList = broacdeBoxDetail.getOrDefault(goodsInfo.getGoodsId(), Collections.emptyList());
            JSONArray bagDetail = new JSONArray();

            Map<Integer, List<GoodsBagInfo>> poolList = new HashMap<>();
            for (GoodsBagInfo goodsBagInfo : goodsBagInfoList) {
                if(!poolList.containsKey(goodsBagInfo.getRandomType())){
                    poolList.put(goodsBagInfo.getRandomType(), new ArrayList<>());
                }
                poolList.get(goodsBagInfo.getRandomType()).add(goodsBagInfo);
            }
            for (Map.Entry<Integer, List<GoodsBagInfo>> entry : poolList.entrySet()) {
                JSONArray pool = new JSONArray();
                for (GoodsBagInfo goodsBagInfo : entry.getValue()) {
                    JSONObject detailObject = new JSONObject();
                    detailObject.put("propId", goodsBagInfo.getGoodsId());
                    detailObject.put("num", goodsBagInfo.getMaxNum());
                    detailObject.put("weight", goodsBagInfo.getRandomWeight());
                    pool.add(detailObject);
                }
                bagDetail.add(pool);
            }
            boxObject.put("brocadeBoxContentList", bagDetail);
            row.add(boxObject);
        }
        result.getData().put("row", row);
        return result;
    }

    /**
     *  48.6 刷新
     */
    @ResponseBody
    @RequestMapping(value = "refreshBrocadeBox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public AdminResult refreshBrocadeBox(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        //刷新区服
        List<ServerInfo> channelServerList = ServerListMgr.getChannelServerList(channelId);

        String msg = CenterReloadHelper.serverMgrReload(channelServerList, "CommonMgr", 30);

        msg += CenterReloadHelper.serverMgrReload(channelServerList, "ServerLanguageMgr", 30);
        AdminResult result = AdminResult.defaultInstance();
        result.setMsg(msg);
        return result;
    }
}
